package com.demo.core;

import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.*;
import org.apache.ibatis.javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.security.sasl.AuthenticationException;
import java.net.SocketTimeoutException;
import java.nio.file.AccessDeniedException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        logger.error(e.getMessage(), e);
        if (e instanceof BusinessException) {
            logger.error("BusinessException occurred: " + e.getMessage());
            return new Result<>(HttpStatus.CONFLICT, e.getMessage(), null, null);
        } else if (e instanceof SystemException) {
            logger.error("SystemException occurred: " + e.getMessage());
            return new Result<>(HttpStatus.SYSTEM_ERROR, e.getMessage(), null, null);
        } else if (e instanceof ParameterException) {
            logger.error("ParameterException occurred"+e.getMessage());
            return new Result<>(HttpStatus.BAD_REQUEST,e.getMessage(), null, null);
        } else {
            logger.error("Unknown exception occurred: " + e.getMessage());
            return new Result<>(HttpStatus.SYSTEM_ERROR, "系统内部异常", null, null);
        }
    }
}
